package com.ig.controller;

import java.io.IOException;
import java.math.BigInteger;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ig.business.BookInfoManager;
import com.ig.model.Book;
import com.ig.model.Search;

public class BulkBooksController extends HttpServlet {
	/**
	 * default serialVersionUID
	 */
	private static final long serialVersionUID = 1L;

	RequestDispatcher dispatcher;

	public void init(ServletConfig config) throws ServletException {
		// can configure loggers & schedulers here
	}

	public void doGet(HttpServletRequest req, HttpServletResponse res)
			throws ServletException, IOException {
		res.setContentType("text/plain");
		String keywords = "";
		BigInteger minPrice = new BigInteger(req.getParameter("minPrice"));
		BigInteger maxPrice = new BigInteger(req.getParameter("maxPrice"));
		String condition = req.getParameter("condition");
		if (req.getParameter("keywords") != null)
			keywords = req.getParameter("keywords");
		// get Books from Book Manager.
		List<Book> books = BookInfoManager
				.getBooksFromAmazon(populateSearchCriteria(condition, keywords,
						minPrice, maxPrice));
		req.getSession().setAttribute("books", books);
		if (books == null)
			req.setAttribute("noBooks", "noBooks");
		dispatcher = req.getRequestDispatcher("/jsp/search.jsp");
		dispatcher.forward(req, res);

	}

	public static Search populateSearchCriteria(String condition,
			String keywords, BigInteger minPrice, BigInteger maxPrice) {
		Search searchCriteria = new Search();
		searchCriteria.setCondition(condition);
		searchCriteria.setKeyWords(keywords);
		searchCriteria.setMaxPrice(maxPrice);
		searchCriteria.setMinPrice(minPrice);
		return searchCriteria;
	}

}
